//
// GNS_IOSHelper.cpp
// MobileManageSys
//
// Created by mr.l on 16/1/15.
//
//

#include "GNS_IOSHelper.h"
USING_NS_CC;

#define winsize Director::getInstance()->getVisibleSize()

GNS_IOSHelper * GNS_IOSHelper::m_Instance =0;

GNS_IOSHelper::GNS_IOSHelper()
{
    
}

GNS_IOSHelper::~GNS_IOSHelper()
{
    
}

GNS_IOSHelper * GNS_IOSHelper::GetInstance()
{
    if (!m_Instance) {
        m_Instance = new GNS_IOSHelper();
    }
    return m_Instance;
}

bool GNS_IOSHelper::GetClipboard(std::string Test)
{
    bool IsSuccessful=false;
    UIPasteboard * pab = [UIPasteboard generalPasteboard];
    NSString * strPath = [NSString stringWithUTF8String:Test.c_str()];
    [pab setString:strPath];
    if (pab!=nil) {
        IsSuccessful=true;
    }else{
        IsSuccessful=false;
    }
    return IsSuccessful;
}

const char *GNS_IOSHelper::getMacAddress()
{
#if (CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
    int					mib[6];
    size_t				len;
    char				*buf;
    unsigned char		*ptr;
    struct if_msghdr	*ifm;
    struct sockaddr_dl	*sdl;
    
    // Management Information Base
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    // 尝试取第一个网络接口(en0)
    if ((mib[5]=if_nametoindex("en0"))==0)
    {
        log("A.if_nametoindex.Error!");
        return "";
    }
    
    // 再取接口结构的长度
    if (sysctl(mib,6,0,&len,0,0)<0)
    {
        log("B.sysctl.Error!");
        return "";
    }
    
    // 分配缓冲区
    if ((buf=(char*)malloc(len))==0)
    {
        log("C.malloc.Error!");
        return "";
    }
    
    // 取接口结构内容填充到缓冲区
    if (sysctl(mib,6,buf,&len,0,0)<0)
    {
        log("D.sysctl.Error!");
        free(buf);
        return "";
    }
    
    ifm = (struct if_msghdr *)buf;
    // sdl指向if_msghdr结构后的第一个套接口地址结构
    sdl = (struct sockaddr_dl *)(ifm+1);
    ptr = (unsigned char *)LLADDR(sdl);
    // NSString *outstring = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X",*ptr,*(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4),*(ptr+5)];
    NSString *outstring = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X",*ptr,*(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4),*(ptr+5)];
    free(buf);
    return [outstring UTF8String];
#endif
    return "";
}

const char *GNS_IOSHelper::getIDFA()
{
#if (CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
    //    //BOOL isIDFATrackingEnabled = [[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled];
    //    NSString *pIDFA = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    //    //SIXLog("isIDFATrackingEnabled[%d].pIDFA[%d]=%s",isIDFATrackingEnabled,[pIDFA length],[pIDFA UTF8String]);
    //    return [pIDFA UTF8String];
    CFUUIDRef puuid = CFUUIDCreate(nil);
    CFStringRef uuidString = CFUUIDCreateString(nil,puuid);
    NSString *result = (NSString *)CFStringCreateCopy(NULL,uuidString);
    CFRelease(puuid);
    CFRelease(uuidString);
    return [[result autorelease] UTF8String];
#endif
    return "";
}